package com.woniu108.order.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu108.carService.commos.dto.AddressInfoDto;
import com.woniu108.carService.commos.dto.AdminInfoDto;
import com.woniu108.carService.commos.dto.OrderScoreDto;
import com.woniu108.carService.commos.dto.UserInfoDto;
import com.woniu108.carService.commos.exception.WoniuException;
import com.woniu108.carService.commos.model.PageForm;
import com.woniu108.carService.commos.model.PageParam;
import com.woniu108.carService.commos.model.Result;
import com.woniu108.carService.commos.util.JWTUtil;
import com.woniu108.carService.commos.util.RedisUtil;
import com.woniu108.carService.commos.util.StaticData;
import com.woniu108.order.client.ExtraClient;
import com.woniu108.order.client.PersonClient;
import com.woniu108.order.model.form.AddOrderScoreForm;
import com.woniu108.order.model.model.OrderScore;
import com.woniu108.order.model.param.AddOrderScoreParam;
import com.woniu108.order.service.OrderScoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 积分兑换订单 前端控制器
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/orderScore")
@Api(tags = "积分订单接口")
public class OrderScoreController {

    @Resource
    private OrderScoreService orderScoreService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private PersonClient personClient;
    @Resource
    private ExtraClient extraClient;
    public String getUserId(String token){
        String refreshToken=redisUtil.getString(token);
        String userId= JWTUtil.parseUserToken(refreshToken).get("userId").toString();
        return userId;
    }

    public String getAdminId(String token){
        String refreshToken=redisUtil.getString(token);
        String adminId= JWTUtil.parseAdminToken(refreshToken).get("adminId").toString();
        return adminId;
    }

    /**
     * 新增积分订单
     * @param form 新增积分订单信息
     * @return result 是否正常访问接口结果
     */
    @PostMapping("/addOrderScore")
    @ApiOperation("新增积分订单")
    public Result addOrderScore(@RequestBody AddOrderScoreForm form){
        AddOrderScoreParam param= BeanUtil.toBean(form,AddOrderScoreParam.class);
        OrderScore orderScore = BeanUtil.toBean(param, OrderScore.class);
        String orderNum= UUID.randomUUID().toString();
        orderScore.setOrderScoreNum(orderNum);
        //积分订单无需经过支付环节，直接定为待收货状态
        orderScore.setOrderScoreState(StaticData.ORDER_PRODUCT_STATE_NO_GET);
        orderScore.setPayTime(LocalDateTime.now());
        orderScoreService.save(orderScore);
        return Result.getResult().setMsg("生成积分订单成功");
    }

    /**
     *  删除个人积分订单
     * @param token
     * @param orderScoreNum 积分订单编号
     * @return result 是否正常访问接口结果
     */
    @GetMapping("/deleteOrderScore")
    @ApiOperation("删除个人积分订单")
    @ApiImplicitParam(name = "orderScoreNum",value = "积分订单编号")
    public Result deleteOrderScore(@RequestHeader String token,String orderScoreNum){
        OrderScore orderScore = orderScoreService.getById(orderScoreNum);
        String userId = this.getUserId(token);
        if(orderScore.getUserId()!=userId) throw new WoniuException("非本人订单",10001);
        if(orderScore.getOrderScoreState()==StaticData.ORDER_PRODUCT_STATE_DELETED) throw new WoniuException("订单状态异常",10001);
        Result<UserInfoDto> result = personClient.getByUserId(userId);
        if(result.getCode()!=200) throw new WoniuException(result.getMsg(),result.getCode());
        orderScore.setOrderScoreState(StaticData.ORDER_PRODUCT_STATE_DELETED);
        orderScoreService.updateById(orderScore);
        return Result.getResult().setMsg("删除个人积分订单成功");
    }

    /**
     * 加载个人积分订单列表
     * @param token
     * @return  List<OrderScoreDto> 个人积分订单
     */
    @GetMapping("/getUserOrderScoreList")
    @ApiOperation("加载个人积分订单列表")
    public Result<List<OrderScoreDto>> getUserOrderScoreList(@RequestHeader String token){
        String userId = this.getUserId(token);
        QueryWrapper<OrderScore> wrapper = new QueryWrapper<OrderScore>();
        wrapper.eq("user_id",userId);
        wrapper.ne("order_score_state",StaticData.ORDER_PRODUCT_STATE_DELETED);
        List<OrderScore> list = orderScoreService.list(wrapper);
        List<OrderScoreDto> dtos = new ArrayList<>();
        for (OrderScore orderScore : list) {
            OrderScoreDto dto = BeanUtil.toBean(orderScore, OrderScoreDto.class);
            Result<AddressInfoDto> addressInfoDtoResult = extraClient.AddressInfoById(dto.getAddressId());
            if(addressInfoDtoResult.getCode()!=200) throw new WoniuException(addressInfoDtoResult.getMsg(),addressInfoDtoResult.getCode());
            dto.setAddressInfo(addressInfoDtoResult.getData());
            Result<UserInfoDto> result = personClient.getByUserId(userId);
            if(result.getCode()!=200) throw new WoniuException(result.getMsg(),result.getCode());
            dto.setUserNickName(result.getData().getUserNickName());
            dtos.add(dto);
        }
        return Result.newListInstance(OrderScoreDto.class).setMsg("加载个人积分订单列表成功").setData(dtos);
    }

    /**
     * 获取页码下的所有积分订单信息
     * @param token
     * @param form 分页信息
     * @return Page<OrderScoreDto> 单页积分订单信息
     */
    @PostMapping("/allOrderScoreList")
    public Result<Page<OrderScoreDto>> allOrderScoreList(@RequestHeader String token, @RequestBody PageForm form){
        PageParam param = BeanUtil.toBean(form, PageParam.class);
        String adminId = this.getAdminId(token);
        if(adminId==null) throw new WoniuException("非管理员账号",10001);
        Result<AdminInfoDto> result = personClient.getByAdminId(adminId);
        if(result.getCode()!=200) throw new WoniuException(result.getMsg(),result.getCode());
        AdminInfoDto adminInfoDto = result.getData();
        if(adminInfoDto.getAdminState()!=StaticData.ADMIN_STATE_NORMAL) throw new WoniuException("管理员状态异常",10001);
        QueryWrapper<OrderScore> wrapper=new QueryWrapper<>();
        //降序排列且不加载删除的订单
        wrapper.orderByDesc("pay_time");
        wrapper.ne("order_score_state",StaticData.ORDER_PRODUCT_STATE_DELETED);
        List<OrderScore> list = orderScoreService.list(wrapper);
        //分页
        Page<OrderScoreDto> page=new Page<>();
        ArrayList<OrderScoreDto> dtos=new ArrayList<>();
        int i=0;
        long total = list.size();
        long pages=total%param.getPageSize()==0?total/param.getPageSize():total/param.getPageSize()+1;
        for (OrderScore OrderScore : list) {
            if(i<param.getPageNum()*param.getPageSize().intValue()&&i>=(param.getPageNum()-1)*param.getPageSize().intValue()){
                OrderScoreDto dto = BeanUtil.toBean(OrderScore, OrderScoreDto.class);
                dtos.add(dto);
            }
            i=i+1;
        }
        page.setCurrent(param.getPageNum());
        page.setSize(param.getPageSize());
        page.setRecords(dtos);
        page.setTotal(total);
        page.setPages(pages);
        return Result.newPageInstance(OrderScoreDto.class).setData(page);
    }

    /**
     * 用户确认积分订单收货
     * @param token
     * @param orderScoreNum 积分订单编号
     * @return result 是否正常访问接口结果
     */
    @GetMapping("/receivedUserOrderScore")
    @ApiOperation("用户确认积分订单收货")
    @ApiImplicitParam(name = "orderScoreNum",value = "积分订单编号")
    public Result receivedUserOrderScore(@RequestHeader String token,String orderScoreNum){
        String userId = this.getUserId(token);
        if(userId==null) throw new WoniuException("非用户账号",10001);
        Result<UserInfoDto> result = personClient.getByUserId(userId);
        if(result.getCode()!=200) throw new WoniuException(result.getMsg(),result.getCode());
        OrderScore orderScore = orderScoreService.getById(orderScoreNum);
        if(ObjectUtil.isEmpty(orderScore)) throw new WoniuException("订单信息不存在",10001);
        if(!orderScore.getUserId().equals(userId)) throw new WoniuException("非本人订单",10001);
        if(orderScore.getOrderScoreState()!=StaticData.ORDER_PRODUCT_STATE_NO_GET) throw new WoniuException("订单状态异常",10001);
        orderScore.setOrderScoreState(StaticData.ORDER_PRODUCT_STATE_GET);
        orderScoreService.updateById(orderScore);
        return Result.getResult().setMsg("确认收货成功");
    }
}

